package cn.hubujyjs.lp.service.impl;

import cn.hubujyjs.lp.utils.R;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hubujyjs.lp.domain.FileTree;
import cn.hubujyjs.lp.service.FileTreeService;
import cn.hubujyjs.lp.mapper.FileTreeMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* @author admin
* @description 针对表【file_tree】的数据库操作Service实现
* @createDate 2023-05-17 18:14:30
*/
@Service
public class FileTreeServiceImpl extends ServiceImpl<FileTreeMapper, FileTree>
    implements FileTreeService{
    @Value("${lp.path}")
    private String basePath;
    @Override
    public R<List<FileTree>> tree() {
        LambdaQueryWrapper<FileTree> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FileTree::getParentId,0);
        List<FileTree> list1 = this.list();
        List<FileTree> fileTrees = this.buildFileTree(list1, 0);
        return R.ok(fileTrees);
    }

    @Override
    public R upload(String path, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String suffix= null;
        if (originalFilename != null) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.fastUUID().toString(true)+suffix;
        String filePath=basePath+path;
        File dir = new File(filePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        try {
            //转存文件
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.ok(fileName);
    }

    /**
     * 组装文件树
     * @param fileList 文件树list
     * @param pid 父id
     * @return 文件树
     */
    public List<FileTree> buildFileTree(List<FileTree> fileList,int pid){
        List<FileTree> list = new ArrayList<>();
        for (FileTree fileTree : fileList) {
            if (fileTree.getParentId()==pid){
                fileTree.setChildren(buildFileTree(fileList,fileTree.getId()));
                list.add(fileTree);
            }
        }
        return list;
    }
}




